﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Eff.Extensions
{
    /// <summary>
    /// Clone展类
    /// </summary>
    public static class Clone
    {
        #region Clone
        /// <summary>
        /// 克隆方法，深拷贝,但对象必须是标记过序列化的
        /// </summary>
        /// <param name="objtype"></param>
        /// <returns></returns>
        public static T CloneType<T>(this T objtype)
        {
            T lstfinal;
            if ((typeof(T).GetType().Attributes & System.Reflection.TypeAttributes.Serializable) != System.Reflection.TypeAttributes.Serializable)
            {
                throw new SerializationException();
            }
            using (var memStream = new MemoryStream())
            {
                var binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
                binaryFormatter.Serialize(memStream, objtype);
                memStream.Seek(0, SeekOrigin.Begin);
                lstfinal = (T)binaryFormatter.Deserialize(memStream);
            }

            return lstfinal;
        }


        #endregion
    }
}
